<template>
    <div :style="{margin: '20px'}">
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-form :inline="true" size="normal">
                <el-form-item label="">
                    <el-input placeholder="用户名" size="small" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button size='small' :style="{fontSize: '14px'}" type="primary" icon="el-icon-search"
                        @click="getUserList()">查询
                    </el-button>
                    <el-button size='small' :style="{fontSize: '14px'}" @click="keyword = ''">清空</el-button>
                </el-form-item>
            </el-form>

            <el-button size='small' :style="{fontSize: '14px'}" type="primary" @click="showAddDialog">添 加
            </el-button>
            <el-button size='small' :style="{fontSize: '14px'}" type="danger" :disabled="!selectedList.length"
                @click="deleteSelectedUser">批量删除</el-button>


            <!-- 必须给所有表格项都设置 width, fixed 才能生效 -->
            <el-table border stripe :style="{margin: '20px 0'}" :data="userList"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align='center'>
                </el-table-column>

                <el-table-column label="序号" align="center" width="80" type="index">
                </el-table-column>

                <el-table-column label="用户名" width="160" prop="username">
                </el-table-column>

                <el-table-column label="用户昵称" width="80" prop='nickName'>
                </el-table-column>

                <el-table-column label="角色列表" width="200" prop="roleName">
                    <template v-slot="{row}">
                        {{row.roleName}}
                    </template>
                </el-table-column>

                <el-table-column label="创建时间" width="180" prop="gmtCreate">
                </el-table-column>

                <el-table-column label="更新时间" width="180" prop="gmtModified">
                </el-table-column>

                <el-table-column label="操作" align="center" fixed="right" width="200">
                    <template v-slot="{row}">
                        <el-button type="info" title="分配角色" size="mini" icon="el-icon-user"
                            @click="showAssignDialog(row)"></el-button>
                        <el-button type="primary" title="修改用户" size="mini" icon="el-icon-edit"
                            @click="showAddDialog(row)"></el-button>
                        <el-button type="danger" title="删除用户" size="mini" icon="el-icon-delete"
                            @click="deleteUser(row.id, false)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination :current-page.sync="page" :total="total" :page-size="limit" :page-sizes="[5, 10, 15, 20]"
                :style="{marginBottom: '50px'}" @current-change="handleCurrentChange"
                layout="prev, pager, next, jumper, ->, sizes, total">
            </el-pagination>


            <!-- 添加和修改用户的弹窗 -->
            <el-dialog :title="userId ? '修改用户' : '添加用户'" :visible.sync="isShowDialog">
                <el-form :model="addOrUpdateForm" ref="addOrUpdateForm" :rules="rules" label-width="100px"
                    :inline="false" size="normal">
                    <el-form-item label="用户名" prop="inpUsername">
                        <el-input size="small" v-model="addOrUpdateForm.inpUsername"></el-input>
                    </el-form-item>

                    <el-form-item label="用户昵称" prop="inpNickName">
                        <el-input size="small" v-model="addOrUpdateForm.inpNickName"></el-input>
                    </el-form-item>

                    <el-form-item label="用户密码" prop="inpPassword" v-show="!userId">
                        <el-input size="small" v-model="addOrUpdateForm.inpPassword"></el-input>
                    </el-form-item>
                </el-form>

                <span slot="footer">
                    <el-button size="small" @click="isShowDialog = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="addOrUpdateUser">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 设置角色的弹窗 -->
            <el-dialog title="设置角色" :visible.sync="isShowAssign">
                <el-form label-width="100px" :inline="false" size="normal">
                    <el-form-item label="用户名">
                        <el-input v-model="addOrUpdateForm.inpUsername" disabled size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="角色列表" size="normal">
                        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                            全选
                        </el-checkbox>
                        <el-checkbox-group v-model="assignIdList" @change="handleCheckedChange">
                            <el-checkbox v-for="role in allRolesList" :key="role.id" :label="role.id">
                                {{role.roleName}}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>

                <span slot="footer">
                    <el-button size="small" @click="isShowAssign = false">取消</el-button>
                    <el-button size="small" type="primary" @click="updateAssign">保存</el-button>
                </span>
            </el-dialog>

        </el-card>

    </div>
</template>
<script>
import { mapGetters, mapState } from 'vuex';
import { Message } from 'element-ui'
import aclUserApi from '@/api/aclUser';

export default {
    name: 'User',
    data() {
        return {
            page: 1,
            limit: 5,
            isShowDialog: false,
            isShowAssign: false,
            addOrUpdateForm: {
                inpUsername: '',
                inpNickName: '',
                inpPassword: '',
            },
            rules: {
                inpUsername: [
                    { required: true, message: '用户名不能为空', trigger: 'blur' }
                ],
                inpPassword: [
                    { required: true, message: '密码不能为空', trigger: 'blur' }
                ]
            },
            keyword: '',
            selectedList: [],
            userId: '',
            assignRoles: [],
            allRolesList: [],
            assignIdList: [],
            checkAll: false,
            isIndeterminate: true
        };
    },
    mounted() {
        this.getUserList()
    },
    methods: {
        // 有用户名就会自动筛选
        getUserList(page = 1) {
            this.page = page
            this.$store.dispatch('aclUser/getUserList', {
                page: this.page,
                limit: this.limit,
                username: this.keyword,
                nickName: ''
            })
        },
        handleCurrentChange(page) {
            this.getUserList(page)
        },
        showAddDialog(row) {
            if (row.id) {
                this.addOrUpdateForm.inpUsername = row.username
                this.addOrUpdateForm.inpNickName = row.nickName
                this.addOrUpdateForm.inpPassword = row.password
                this.userId = row.id
                this.isShowDialog = true
            } else {
                if (this.$refs.addOrUpdateForm) this.$refs.addOrUpdateForm.resetFields();
                // this.addOrUpdateForm.inpUsername = ''
                // this.addOrUpdateForm.inpNickName = ''
                // this.addOrUpdateForm.inpPassword = ''
                this.userId = ''
                this.isShowDialog = true
            }
        },
        async addOrUpdateUser() {
            this.$refs.addOrUpdateForm.validate(async (val, error) => {
                if (val) {
                    let { inpUsername, inpPassword, inpNickName } = this.addOrUpdateForm
                    if (this.userId) {
                        try {
                            await this.$store.dispatch('aclUser/updateUser', { id: this.userId, username: inpUsername, password: inpPassword, nickName: inpNickName })
                            Message.success('修改用户成功')
                            this.getUserList()
                            this.isShowDialog = false
                        } catch (error) {
                            Message.error('修改用户失败')
                        }
                    } else {
                        try {
                            await this.$store.dispatch('aclUser/addUser', { username: inpUsername, password: inpPassword, nickName: inpNickName })
                            Message.success('添加用户成功')
                            this.getUserList()
                            this.isShowDialog = false
                        } catch (error) {
                            Message.error('添加用户失败')
                        }
                    }
                } else {
                    console.log('failed');
                    return false
                }
            })

        },
        async deleteUser(id, isSelected) {
            try {
                const result = await aclUserApi.deleteUser(id)
                if (result.code === 20000) {
                    // 删除单个走上面
                    // 批量删除走下面
                    if (!isSelected) {
                        Message.success('删除成功')
                        this.getUserList()
                    } else {
                        return 'ok'
                    }
                } else {
                    if (!isSelected) {
                        Message.error('删除失败')
                    } else {
                        return Promise.reject(new Error('failed'))
                    }
                }
            } catch (error) {
                if (!isSelected) {
                    Message.error('请求删除失败')
                } else {
                    return Promise.reject(new Error('failed'))
                }
            }
        },
        handleSelectionChange(selection) {
            this.selectedList = selection
        },
        async deleteSelectedUser() {
            let PromiseList = []
            this.selectedList.forEach(item => {
                let promise = this.deleteUser(item.id, true)
                PromiseList.push(promise)
            })
            try {
                await Promise.all(PromiseList)
                Message.success('批量删除成功')
                this.getUserList()
            } catch (error) {
                Message.success('请求批量删除失败')
            }
        },
        async showAssignDialog(row) {
            try {
                const result = await aclUserApi.getUserAssign(row.id)
                if (result.code === 20000) {
                    this.assignRoles = result.data.assignRoles
                    this.allRolesList = result.data.allRolesList
                } else {
                    Message.error('获取用户权限列表失败')
                }
            } catch (error) {
                Message.error('请求获取用户权限列表失败')
            }

            this.userId = row.id
            this.addOrUpdateForm.inpUsername = row.username
            this.assignIdList = this.assignRoles.map(item => item.id)
            this.checkAll = this.assignIdList.length === this.allRolesList.length
            this.isIndeterminate = this.assignIdList.length > 0 && this.assignIdList.length < this.allRolesList.length
            this.isShowAssign = true
        },
        handleCheckedChange(val) {
            // assignRoles 当前用户角色
            // allRolesList 所有角色列表
            // assignIdList 选中角色的id数组
            this.assignIdList = val
            // 是否全选和是否有选中
            this.checkAll = this.assignIdList.length === this.allRolesList.length
            this.isIndeterminate = this.assignIdList.length > 0 && this.assignIdList.length < this.allRolesList.length
        },
        handleCheckAllChange(val) {
            this.isIndeterminate = false
            this.assignIdList = val ? this.allRolesList.map(item => item.id) : []
        },
        async updateAssign() {
            try {
                const result = await aclUserApi.updateAssign(this.userId, this.assignIdList.join(','))
                if (result.code === 20000) {
                    Message.success('分配角色成功')
                    this.getUserList(this.page)
                    this.isShowAssign = false
                } else {
                    Message.success('分配角色失败')
                }
            } catch (error) {
                Message.success('请求分配角色失败')
            }
        },
    },
    computed: {
        ...mapState('aclUser', ['userList', 'total']),
    }
}

</script>

<style lang='less' scoped>

</style>
